package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.database.Database;
import com.conversationboard.model.Message;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;
import com.conversationboard.model.adminlog.AdminLog;
import com.conversationboard.model.yellowcardlog.YellowCardLog;

@WebServlet(name = "AdminYellowCardControllerServlet", urlPatterns = "/Admin/AdminYellowCardControllerServlet")
public class AdminYellowCardControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 4236989023330513518L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());
			int boardId = Integer.parseInt(request.getParameter("boardid"));
			int threadId = Integer.parseInt(request.getParameter("threadid"));
			int messageId = Integer.parseInt(request.getParameter("messageid"));
			User userToBeYellowCarded = User.get(request.getParameter("loginid"));
			String reason = request.getParameter("reason");

			if (!user.isBoardAdmin(boardId)) {
				return;
			}

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			Connection connection = null;

			try {

				connection = Database.getConnection();
				connection.setAutoCommit(false);

				userToBeYellowCarded.yellowCard(connection, reason);
				AdminLog.getInstance().write(connection, user, boardId, "User <strong>" + userToBeYellowCarded.getFullDisplayName() + "</strong> has been Yellow Carded" + "<p>" + reason + "</p>");

				Thread thread = Thread.get(boardId, threadId);
				Message message = thread.getMessage(messageId);

				YellowCardLog.write(connection, request.getParameter("loginid"), reason, boardId, threadId, messageId, message.getBody(), user.getLoginId());

				connection.commit();

			} catch (SQLException e) {
				connection.rollback();
				throw e;
			} catch (NoSuchThreadException e) {
				connection.rollback();
				throw e;
			} finally {
				Database.close(connection);
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			request.setAttribute("message", "User has been yellow carded.");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (NoSuchThreadException e) {
			throw new ServletException(e);
		}

	}

}